package lzq.aop.config;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.CannotGetJdbcConnectionException;

public class DataSourceUtils {

	private static ThreadLocal<Connection> connectionContainer = new ThreadLocal<>();


	/**
	 * 获取数据库链接并绑定到当前线程
	 * 
	 * @return
	 * @throws CannotGetJdbcConnectionException
	 */
	public static Connection getConnection(DataSource dataSource) throws CannotGetJdbcConnectionException {
		try {
			Connection conToUse = connectionContainer.get();
			if (conToUse == null || conToUse.isClosed()) {
				conToUse = dataSource.getConnection();
				connectionContainer.set(conToUse);// 将此连接绑定到当前线程上

			}
			return conToUse;
		} catch (SQLException ex) {
			throw new CannotGetJdbcConnectionException("Could not get JDBC Connection", ex);
		}
	}

	/*** 获取当前线程上的连接开启事务 */
	public static void startTransaction(DataSource dataSource) {
		Connection conn = connectionContainer.get();// 首先获取当前线程的连接
		if (conn == null) {// 如果连接为空
			conn = getConnection(dataSource);// 从连接池中获取连接
			System.out.println("线程"+Thread.currentThread().getName() + " 空连接从dataSource获取连接");
		} else {
			System.out.println("线程"+Thread.currentThread().getName() + "从缓存中获取连接");
		}
		try {
			System.out.println("开启事务，修改自动提交为false.");
			conn.setAutoCommit(false);// 开启事务
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 提交事务
	public static void commit() {
		try {
			Connection conn = connectionContainer.get();// 从当前线程上获取连接if(conn!=null){//如果连接为空，则不做处理
			if (null != conn) {
				conn.commit();// 提交事务
				System.out.println(Thread.currentThread().getName() + "事务已经提交......");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*** 回滚事务 */
	public static void rollback() {
		try {
			Connection conn = connectionContainer.get();// 检查当前线程是否存在连接
			if (conn != null) {
				conn.rollback();// 回滚事务
				connectionContainer.remove();// 如果回滚了，就移除这个连接
				close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*** 关闭连接 */
	public static void close() {
		System.out.println("关闭或者归还连接");
		try {
			Connection conn = connectionContainer.get();
			if (conn != null && !conn.isClosed()) {
				 conn.close();
				 connectionContainer.remove();
				System.out.println(Thread.currentThread().getName() + "连接关闭");
			}
		} catch (SQLException e) {
			throw new RuntimeException(e.getMessage(), e);
		} finally {
			try {
				connectionContainer.remove();// 从当前线程移除连接!!
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

}
